<?php if (defined("YTDJ") or die()); 

Class SearchController extends Controller {

	function yt() {
		$q = Request::get("q");
				
		$this->startindex = Request::get("start");
		if (empty($this->startindex)) {
			$this->startindex = 1;
		}
		
		$this->videos = YouTube::getVideos($q, $this->startindex, Config::getInstance()->maxResults);		
		$this->display();
	}
	
	function yt_getsimilar() {
		global $tryLFMSearchTimes;
		
		// get vid id
		$vidid = $_POST["q"];		
		if (!$vidid) { $vidid = $_GET["q"]; }
		if (!$vidid) { return false; }
		
		// get artist from session
		$artist = trim($_SESSION[$vidid]["artist"]);
		
		// get similar artists
		$this->artists = FeedLFM::getSimilarArtists($artist);
		
		// no similar artist result?
		if ($this->artists) { 
		
			$break = false;
			$loopCount = 0;
			
			// first ten result
			$this->artists = array_slice($this->artists, 0, 10);
					
			do {
				
				// break by default
				$break = false;
				
				// random get one similar artist
				$randnmb = (integer) rand(0, count($this->artists)-1);
				$similarartist = $this->artists[$randnmb];
				
				// get videos
				$this->videos = FeedYT::getVideos($similarartist, 1, 10);
				
				// don't break if no video's are found
				if ($this->videos) {
					
					$break = true;
							
					// another random, video this time
					$randnmb = (integer) rand(0, count($this->videos)-1);
					$video = $this->videos[$randnmb];
					
					// store array in session
					$_SESSION[$video["id"]] = $video;
					
					$this->vidid = $video["id"];
					
				}
					
				$loopCount++;
			
				if ($loopCount > $tryLFMSearchTimes) {
					echo 'too many tries, stopping';
					$break = true;
				}
								
			} while ($break = false);
			
		}

		if (!$this->vidid) {
			// no video's or similar artists found	
			
			// load vid from same query
			$query = trim($_SESSION[$vidid]["q"]);
			$vids = $_SESSION;
			shuffle($vids);
			
			foreach ($vids as $vid) {
				if ($vid["q"] == $query && $vid["id"] != $vidid) {					
					$this->vidid = $vid["id"];
					break;
				}
			}
		}
		
		if (!$this->vidid) {
			// now we have really a problem
			echo "NO VID FOUND!";
			exit();
		}
		
		$this->loadTemplate("playlistentry"); 
		$this->display();
		
	}	
}

?>